package com.zhiyou.app.shop.website.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhiyou.app.shop.common.util.Page;
import com.zhiyou.app.shop.website.dao.IUserStockDao;
import com.zhiyou.app.shop.website.dao.IUserStockInfoDao;
import com.zhiyou.app.shop.website.dao.pojo.ActivityApply;
import com.zhiyou.app.shop.website.dao.pojo.UserStock;
import com.zhiyou.app.shop.website.dao.pojo.UserStockInfo;
import com.zhiyou.app.shop.website.service.IUserStockInfoService;

@Service(value="userStockInfoService")
public class UserStockInfoServiceImpl implements IUserStockInfoService {

	@Autowired
	private IUserStockInfoDao userStockInfoDao;
	@Autowired
	private IUserStockDao userStockDao;
	
	public BigDecimal getAviSaleStock(String userId, BigDecimal saleDay, String date) {
		BigDecimal saled = userStockInfoDao.findAllSaleByDay(userId, date);
		if(saleDay.compareTo(saled) == 0){
			return BigDecimal.ZERO;
		}else if(saleDay.compareTo(saled) == 1){
			return saleDay.subtract(saled);
		}
		return BigDecimal.ZERO;
	}

	public Integer getListedQua(String userId) {
		return userStockInfoDao.listed(userId);
	}

	public void findUserStock(Page page, String userAccount, String type,
			String price1,String price2,String startDate, String endDate, String status) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserStockInfo.class);
		if(userAccount != null && !"".equals(userAccount)){
			criteria.add(Expression.like("userId", userAccount));
		}
		if(type != null && !"".equals(type)){
			criteria.add(Expression.like("type", type));
		}
		if(price1 != null && !"".equals(price1)){
			criteria.add(Expression.between("price", new BigDecimal(price1), new BigDecimal(price2)));
		}
		if(startDate != null && !"".equals(startDate)){
			criteria.add(Expression.between("createDate", Timestamp.valueOf(startDate), Timestamp.valueOf(endDate)));
		}
		userStockInfoDao.findByCriteria(page, criteria, Order.desc("createDate"));
	}

	public List<Map<String, Object>> findStockInfo(String stockType,
			String userType, Page page) {
		return this.userStockInfoDao.findStockInfo(stockType, userType, page);
	}

	public int findStockInfoCount(String stockType, String userType) {
		return this.userStockInfoDao.findStockInfoCount(stockType, userType);
	}

	public Long findStockNum(String account) {
		List<UserStock> list = userStockDao.findByProperty("userId", account);
		if(list != null && list.size() > 0){
			return list.get(0).getStockNum();
		}
		return 0l;
	}

}
